package cn.yujiago.miaosha.interceptor;

import cn.yujiago.miaosha.component.UserContext;
import cn.yujiago.miaosha.constant.UserConstant;
import cn.yujiago.miaosha.entity.User;
import cn.yujiago.miaosha.service.UserService;
import cn.yujiago.miaosha.util.CookieUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

        // 取出参数或Cookie中的token
        String paramToken = httpServletRequest.getParameter(UserConstant.COOKIE_NAME_TOKEN);
        String cookieToken = CookieUtil.getValueByKey(httpServletRequest, UserConstant.COOKIE_NAME_TOKEN);

        if(StringUtils.isEmpty(cookieToken) && StringUtils.isEmpty(paramToken)) {
            httpServletResponse.sendRedirect("/page/login.htm");
            return false;
        }else{
            String token = StringUtils.isEmpty(paramToken)?cookieToken:paramToken;
            // 使用token去redis缓存中查找User信息
            User user = userService.getByToken(httpServletResponse, token);
            if(user == null){
                httpServletResponse.sendRedirect("/page/login.htm");
                return false;
            }else{
                UserContext.setUser(user);
                return true;
            }
        }
    }
}
